package com.zhoutao.blog.seven.service.impl;

import com.zhoutao.blog.seven.dao.repository.ArticleRepository;
import com.zhoutao.blog.seven.dao.repository.BlogCategoryRepository;
import com.zhoutao.blog.seven.model.converter.BlogCategoryConverter;
import com.zhoutao.blog.seven.model.detail.BLogCategoryDetail;
import com.zhoutao.blog.seven.model.response.BLogCategory;
import com.zhoutao.blog.seven.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    private final BlogCategoryRepository categoryRepository;

    private final BlogCategoryConverter converter;

    private final ArticleRepository articleRepository;

    @Override
    public List<BLogCategory> list() {
        List<BLogCategory> categories = categoryRepository.list().stream().map(converter::converterFrom).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(categories)) {
            return Collections.emptyList();
        }


        List<Long> categoryIds = categories.stream().map(BLogCategory::getId).collect(Collectors.toList());
        Map<Long, Long> countMap = articleRepository.count(categoryIds);

        return categories.stream().map(category -> {
            Long articleCount = countMap.getOrDefault(category.getId(), 0L);
            return new BLogCategoryDetail(category, articleCount);
        }).collect(Collectors.toList());
    }
}
